<template>
    <div class="container-wrapper">
            <date-picker-summary @filterChange="getInit"></date-picker-summary>
          
        <el-row style="white-space: pre-line;" v-show="filters.radio">           
            <el-row>
                <el-col :xs="24" :sm="24" :lg="24">
                    <div class="ibox">
                        <div class="ibox-title">
                            <h5>项目汇总</h5>
                        </div>
                        <div class="ibox-content">
                        <el-row>
                            <el-col :xs="6" :sm="6" :lg="6">
                                <small class="stats-label">项目总数</small>
                                <h4>{{ total_project_count }}</h4>
                            </el-col>
                            <el-col :xs="6" :sm="6" :lg="6">
                                <small class="stats-label">实施中</small>
                                <h4>{{ active_project_count }}</h4>
                            </el-col>
                            <el-col :xs="6" :sm="6" :lg="6">
                                <small class="stats-label">超投</small>
                                <h4>0</h4>
                            </el-col>
                            <el-col :xs="6" :sm="6" :lg="6">
                                <small class="stats-label">进度异常</small>
                                <h4>0</h4>
                            </el-col>
                        </el-row>
                        </div>
                        <div class="ibox-content">
                            <el-row>
                                <el-col :xs="6" :sm="6" :lg="6">
                                    <small class="stats-label">总利润</small>
                                    <h4>0</h4>
                                </el-col>
                                <el-col :xs="6" :sm="6" :lg="6">
                                    <small class="stats-label">实施项目总利润</small>
                                    <h4>0</h4>
                                </el-col>
                                <el-col :xs="6" :sm="6" :lg="6" style="cursor: pointer">
                                    <div @click="dialogTableVisible = true">
                                        <small class="stats-label">累计工时</small>
                                        <h4>{{ workingHours }}</h4>
                                    </div>
                                </el-col>
                            </el-row>
                        </div>
                    </div>
                </el-col>
            </el-row>

            <el-row :gutter="30">
                <el-col :xs="24" :sm="24" :lg="8">
                    <div class="ibox">
                        <div class="ibox-title">
                        <h5>项目等级分布</h5> 
                        </div>
                        <div class="ibox-content">
                            <ve-pie :data="chartData" :settings="chartSettings"></ve-pie>
                        </div>
                    </div>
                </el-col>

                <el-col :xs="24" :sm="24" :lg="8">
                    <div class="ibox">
                        <div class="ibox-title">
                        <h5>事业部分布</h5> 
                        </div>
                        <div class="ibox-content">
                            <ve-pie :data="chartData1" :settings="chartSettings"></ve-pie>                    
                        </div>
                    </div>
                </el-col>

                <el-col :xs="24" :sm="24" :lg="8">
                    <div class="ibox">
                        <div class="ibox-title">
                        <h5>项目状况分布</h5> 
                        </div>
                        <div class="ibox-content">
                            <ve-pie :data="chartData2" :settings="chartSettings"></ve-pie>                    
                        </div>
                    </div>
                </el-col>
            </el-row>

            <el-row :gutter="30">
                <el-col :xs="24" :sm="24" :lg="8">
                    <div class="ibox">
                        <div class="ibox-title">
                        <h5>人员投入分布饼图</h5> 
                        </div>
                        <div class="ibox-content">
                            <ve-pie :data="workPie" :settings="workSettings"></ve-pie>                    
                        </div>
                    </div>
                </el-col>

                <el-col :xs="24" :sm="24" :lg="16">
                    <el-card class="box-card m-b" shadow="never">
                        <div slot="header" class="clearfix" style="vertical-align:middle">
                            <div style="float: left; padding: 10px 0">人员投入分布柱状图</div>
                            <el-radio-group @change="workChange" v-model="work" style="float: right; padding: 3px 0" size="mini">
                                <el-radio-button label="按月"></el-radio-button>
                                <el-radio-button label="按天"></el-radio-button>
                            </el-radio-group>                 
                        </div>
                        <div>
                            <ve-histogram
                                :data="workTrend"
                                :settings="workSettings"                                
                                :data-empty="workDataEmpty"
                                :loading="workLoading"
                                :data-zoom="dataZoom">
                            </ve-histogram>
                        </div> 
                    </el-card>                
                </el-col>
            </el-row>            

            <el-row>
                <!-- 项目信息列表 -->
                <el-col :xs="24" :sm="24" :lg="24">
                    <div class="ibox">
                        <div class="ibox-title">
                        <h5>项目信息列表</h5> 
                        </div>
                        <div class="ibox-content">
                            <!-- <div class="search-Box" style="width: 300px; float: right">
                                <el-input placeholder="输入关键字搜索" prefix-icon="el-icon-search"  class="search" size="mini">
                                </el-input>
                            </div> -->
                            <!-- <el-button @click="clearFilter">清除所有过滤器</el-button> -->
                            <el-table
                                ref="filterTable"
                                :data="tableData"
                                style="width: 100%">
                                <el-table-column
                                    label="项目名称"
                                    width="120"
                                    fixed>
                                    <template slot-scope="sub">
                                        <el-button type="text" size="small" @click="redirect(sub.row.project_id, sub.row.project_name)">
                                            {{ sub.row.project_name }}
                                        </el-button>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="projectinfo.project_code"
                                    label="项目编码"
                                    width="120"
                                    column-key="project_code"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="project_period"
                                    width="100"
                                    label="项目周期">
                                </el-table-column>
                                <el-table-column
                                    prop="profit_rate"
                                    label="利润率"
                                    width="100">
                                </el-table-column>
                                <el-table-column             
                                    width="100"
                                    label="当前阶段">
                                    <template slot-scope="scope">
                                        <span v-if="scope.row.projectinfo.project_cur_phase == 'undefined' || scope.row.projectinfo.project_cur_phase == 'Undefined'"></span>
                                        <span v-else>{{ scope.row.projectinfo.project_cur_phase }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="progress_baseline"
                                    label="进度基准"
                                    width="100">
                                </el-table-column>
                                <el-table-column
                                    prop="progress"
                                    label="实际进度"
                                    width="100">
                                </el-table-column>
                                <el-table-column
                                    prop="progress_exception"
                                    label="进度异常"
                                    width="100">
                                </el-table-column>
                                <el-table-column
                                    prop="address"
                                    label="当前投入人月/总投入人月"
                                    width="200">
                                </el-table-column>
                                <el-table-column
                                    prop="address"
                                    width="100"
                                    label="超投">
                                </el-table-column>
                                <el-table-column
                                    prop="project_stats.project_req_rate"
                                    width="100"
                                    label="需求率"
                                    :formatter="formatter_rate">
                                </el-table-column>
                                <el-table-column
                                    prop="project_stats.project_dev_rate"
                                    width="100"
                                    label="开发率"
                                    :formatter="formatter_rate">
                                </el-table-column>
                                <el-table-column
                                    prop="project_stats.project_test_rate"
                                    width="100"
                                    label="测试率"
                                    :formatter="formatter_rate">
                                </el-table-column>
                                <el-table-column
                                    prop="project_stats.project_bug_close_rate"
                                    width="100"
                                    label="缺陷关闭率"
                                    :formatter="formatter_rate">
                                </el-table-column>
                                <el-table-column
                                    prop="address"
                                    width="100"
                                    label="延期票数">
                                </el-table-column>
                                <el-table-column
                                    prop="project_stats.proejct_delay_task_rate"
                                    width="100"
                                    label="延期任务率"
                                    :formatter="formatter_rate">
                                </el-table-column>
                                <el-table-column
                                    prop="address"
                                    width="100"
                                    label="说明">
                                </el-table-column>
                            </el-table>
                            <el-pagination
                                style="padding-top: 10px;"
                                background
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                :current-page="currentPage"
                                :page-sizes="[5, 10, 20]"
                                :page-size="page_size"
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="total">
                            </el-pagination>
                        </div>
                    </div>
                </el-col>
            </el-row>
        </el-row>

        <div v-show="!filters.radio">
            <projected v-if="!filters.radio"></projected>
        </div>
        <!-- 弹出table -->
        <el-dialog :visible.sync="dialogTableVisible">
            <v-dialog 
                :tableList="tableList" 
                :tableListLabel="tableListLabel">
            </v-dialog>
        </el-dialog>
    </div>
</template>
<script>
import DatePicker from '@/components/qa/DatePickerMulti.vue'
import ElDatePicker from '@/components/qa/ElDatePickerMulti.vue'
import DatePickerSummary from './summary/DatePickerSummary.vue';
import { mapState, mapMutations } from 'vuex'
import { getToken, getName } from '@/utils/auth'
import { getHeader } from '@/app.config'
import http from '@/views/sys/axios'
import projected from '@/views/ProjectSummary3';
import VDialog from '@/views/qa/dialog'

export default {
    components: {
        DatePicker,
        ElDatePicker,
        VDialog,
        projected,
        DatePickerSummary
    },
    data () {
        return {
            user: JSON.parse(localStorage.getItem('user')),
            token: getToken(),
            userName: getName(),
            workingHours: 0,
            dialogTableVisible: false,
            tableList: [],
            dataZoom: [{
              type: 'slider',
              start: 0,
              end: 100
            }],
            total_project_count: 0,
            active_project_count: 0,
            workLoading: false,
            workDataEmpty: false,
            workTrend: {
                columns: ['date', 'labor_hours'],
                rows: []
            },
            workPie: {
                columns: ['project_name', 'labor_hours'],
                rows: []
            },
            workSettings: {
                labelMap: {
                    date: '日期',
                    labor_hours: '工时(人/月)',
                    project_name: '项目名'
                }
            },
            type: '',
            work: '按月',
            tableListLabel: [
                {
                    label: '日期',
                    param: 'labor_hour_date',
                    align: 'center'
                },
                {
                    label: '项目',
                    param: 'project',
                    align: 'center'
                },
                {
                    label: '人数',
                    param: 'people_count',
                    align: 'center',
                    render: (row) => {
                        if(row.people_count) {
                            return row.people_count + '人'
                        } else {
                            return 0
                        }						
					}
                },
                {
                    label: '工时',
                    param: 'labor_hours',
                    align: 'center',
                    render: (row) => {
                        if(row.labor_hours) {
                            return row.labor_hours + '小时'
                        } else {
                            return 0
                        }						
					}
                }
                ],
            // radio: this.filters.radio,
            currentPage: 1,
            page_size: 10,
            total: 0,
            departmentIds: '',
            date: '',
            user_project_stats: {},
            chartData: {
                columns: ['project_level', 'p_projid__count'],
                rows: []
            },
            chartData1: {
                columns: ['department_name', 'p_projid__count'],
                rows: []
            },
            chartData2: {
                columns: ['p_cur_phase', 'p_projid__count'],
                rows: []
            },
            chartData3: {
                columns: ['项目', '工时'],
                rows: []
            },
            chartData4: {
                columns: ['项目', '工时'],
                rows: []
            },
            tableData: [],
            chartSettings: {
                radius: 90,
            },
      }
    },
    props: {
        changed: Boolean
    },
    inject: ['reload'],
    methods: {
        getInit() {
            if(this.filters.radio) {                    
                this.getWoringHours()
                this.getHoursTrend()
                this.getPie()
            }
            this.getUserProjStats(this.token, this.filters.departmentId)
        },
        getNetxData() {
            this.getDepartmentLevelDistribution(this.user_project_stats.projMapList.activeIds);
            this.getDepartmentDeptDistribution(this.user_project_stats.projMapList.activeIds);
            this.getDepartmentStageDistribution(this.user_project_stats.projMapList.activeIds);
            this.getDepartmentProjectStats(this.user_project_stats.projMapList.activeIds,1,this.filters.time,this.page_size);
        },
        workChange(val) {
            val == '按月' ? this.type = 'month' : this.type = 'day'
            this.getHoursTrend()
        },
        resetDateFilter() {
            this.$refs.filterTable.clearFilter('date');
        },
        clearFilter() {
            this.$refs.filterTable.clearFilter();
        },
        formatter(row, column) {
            return row.address;
        },
        getWoringHours() {
            http.get(`${process.env.VUE_APP_KANBAN_HOST}/api/resource/labor/input/summary?department=${this.filters.departmentId}&date=${this.filters.time}`)
            .then(res => {
                if(res.code === 200) {
                    this.workingHours = res.total_hours + '人/月'
                    this.tableList = res.labor_details
                }
            })
        },
        getPie() {
            http.get(`${process.env.VUE_APP_KANBAN_HOST}/api/resource/labor/input/distribute?department=${this.filters.departmentId}&date=${this.filters.time}`)
            .then(res => {
                if(res.code === 200) {
                    this.workPie.rows = res.distribute_data.slice(0, 15)
                }
            }).catch(err => {
                console.log(err)
            })
        },
        getHoursTrend() {
            this.workLoading = true
            http.get(`${process.env.VUE_APP_KANBAN_HOST}/api/resource/labor/input/trend?department=${this.filters.departmentId}&date=${this.filters.time}&type=${this.type}`)
            .then(res => {
                if(res.code === 200) {
                    this.workLoading = false
                    this.workTrend.rows = res.data
                    if(!this.workTrend.rows.length) {
                        this.workDataEmpty = true
                    } else {
                        this.workDataEmpty = false
                    }
                } else {
                    this.workLoading = false
                    this.workDataEmpty = true
                }
            }).catch(error => {
                this.workLoading = false
                this.workDataEmpty = true
            })
        },
        filterTag(value, row) {
            return row.tag === value;
        },
        filterHandler(value, row, column) {
            const property = column['property'];
            return row[property] === value;
        },
        getDepartmentIds(departmentIds) {
            this.departmentIds = departmentIds;
        },
        getDate(date) {
            this.date = date;
        },
        getDepartmentLevelDistribution: function(projects) {
            let url = `${process.env.VUE_APP_KANBAN_HOST}/api/qa/getdeptprojlvdistribution`
            let data = {"projects": projects};
            this.$axios.post(url, data, {headers: getHeader()})
                .then((response) => {
                    if (response.status == 200) {
                        this.chartData.rows = response.data.stats;
                    }
                })
                .catch((err) => {
                    // eslint-disable-next-line
                    console.log(err);
                });
        },
        getDepartmentDeptDistribution: function(projects) {
            let url = `${process.env.VUE_APP_KANBAN_HOST}/api/qa/getdeptprojdpdistribution`
            let data = {"projects": projects};
            this.$axios.post(url, data, {headers: getHeader()})
                .then((response) => {
                    if (response.status == 200) {
                        this.chartData1.rows = response.data.stats;
                    }
                })
                .catch((err) => {
                    // eslint-disable-next-line
                    console.log(err);
                });
        },
        getDepartmentStageDistribution: function(projects) {
            let url = `${process.env.VUE_APP_KANBAN_HOST}/api/qa/getdeptprojstgdistribution`
            let data = {"projects": projects};
            this.$axios.post(url, data, {headers: getHeader()})
                .then((response) => {
                    if (response.status == 200) {
                        this.chartData2.rows = response.data.stats;
                    }
                })
                .catch((err) => {
                    // eslint-disable-next-line
                    console.log(err);
                });
        },
        getDepartmentProjectStats: function(projects, page, day, limit=10) {
            let data = {"projects": projects};
            this.$axios.post(process.env.VUE_APP_KANBAN_HOST+'/api/qa/getdeptprojinfo?page='+page+'&limit='+limit+'&day='+day, data, {headers: getHeader()})
                .then((response) => {
                    if (response.status == 200) {
                        this.tableData = response.data.stats;
                        this.total = response.data.count;
                    }
                })
                .catch((err) => {
                    // eslint-disable-next-line
                    console.log(err);
                });
        },
        getUserProjStats: function(token, department) {
            this.$axios.get(process.env.VUE_APP_KANBAN_HOST+'/api/qa/getuserprojstats?token='+token+'&department='+department, {headers: getHeader()})
                .then((response) => {
                    if (response.status == 200) {
                        this.user_project_stats = response.data.project_stats;

                        var active_project_count = this.user_project_stats.projNum.activeIdsnum
                        var clouse_project_count = this.user_project_stats.projNum.closeIdsnum
                        this.total_project_count = active_project_count + clouse_project_count
                        this.active_project_count = active_project_count

                        this.getNetxData() //后续4个接口
                    }
                })
                .catch((err) => {
                    // eslint-disable-next-line
                    console.log(err);
                });
        },
        redirect(projectId, projectName) {
            let time, departmentId = '', departList = [], boolRadio, dateTimes = []      
           
            time = this.filters.time            
            dateTimes = this.filters.dateTimes            
            boolRadio = !this.filters.radio
            departmentId = this.filters.departmentId
            departList = this.filters.departList
            this.setParams({
                time,
                departmentId,
                departList,
                projectName,
                projectId,
                radio: boolRadio,
                dateTimes
            })
            this.reload()
        },
        handleSizeChange(val) {           
            this.page_size = val;
            this.getDepartmentProjectStats(this.user_project_stats.projMapList.activeIds,1,this.filters.time,this.page_size);
        },
        handleCurrentChange(val) {        
            this.currentPage = val;
            this.getDepartmentProjectStats(this.user_project_stats.projMapList.activeIds,this.currentPage,this.filters.time,this.page_size);
        },
        formatter_rate(row, column, cellValue, index) {
            var str = Number(cellValue*100).toFixed(2);
            str += "%";
            return str;
        },
        ...mapMutations([
            'setParams',
            'setAll'
        ])
    },
    computed: {
        ...mapState({
            filters: state => state.filters,
            allDepartmentList: state => state.allDepartmentList
        }),
        // total_project_count() {
        //     if (this.user_project_stats) {
        //         if (this.user_project_stats.projNum) {
        //             var active_project_count = this.user_project_stats.projNum.activeIdsnum;
        //             var clouse_project_count = this.user_project_stats.projNum.closeIdsnum;
        //             var total = active_project_count + clouse_project_count;
        //             return total
        //         }    
        //     }
        // },
        // active_project_count() {
        //     if (this.user_project_stats) {
        //         if (this.user_project_stats.projNum) {
        //             var active_project_count = this.user_project_stats.projNum.activeIdsnum;
        //             return active_project_count;
        //         }
        //     }
        // }
    },
    watch: {
        // filters: {
        //     handler: function(val,old) {     
        //         console.log('watchdep2',val)     
        //         if(this.filters.radio) {                    
        //             this.getWoringHours()
        //             this.getHoursTrend()
        //             this.getPie()
        //         }
        //         this.getUserProjStats(this.token, this.filters.departmentId)
                             
        //     }    
        // },
        // 'user_project_stats.projMapList': {
        //     handler: function() {
                
        //     },
        //     deep: true
        // }
    },  
    mounted() {
        
        // if(this.filters.radio) {
        //     // this.getWoringHours()
        //     // this.getDepartment(this.token, this.userName)           
        //     this.getUserProjStats(this.token, this.filters.departmentId)
        // }  
        // this.$nextTick(() => {
        //     console.log('mounte',this.filters)
        //     console.log('mounte',this.$store.getters.filters)

            
        //     this.getInit() 
        // })
                
    },
    // beforeUpdate() {
    //     console.log('beforeUpdate',this.filters)
    //     this.getInit()   
    // }
}
</script>

<style lang="scss" scoped>
    @import '../assets/common/common.scss';
    .container-wrapper {
        padding: 32px;
        background-color: rgb(240, 242, 245);
        position: relative;
        p{ 
            white-space: pre-wrap; 
        }
    }
    .ibox{
        clear: both;
        margin-bottom: 25px;
        margin-top: 0;
        padding: 0;
    }
    .ibox-title{
        background-color: #ffffff;
        border-color: #e7eaec;
        border-image: none;
        border-style: solid solid none;
        border-width: 2px 0 0;
        color: inherit;
        margin-bottom: 0;
        padding: 15px 90px 8px 15px;
        min-height: 48px;
        position: relative;
        clear: both;
    }
    .ibox-title h5{
        display: inline-block;
        font-size: 14px;
        margin: 0 0 7px;
        padding: 0;
        text-overflow: ellipsis;
        float: none;
    }
    .ibox-title a{
        color: #337ab7;
        cursor: pointer;
        font-size: 13px;
    }
    .ibox-content {
        background-color: #ffffff;
        color: inherit;
        padding: 15px 20px 20px 20px;
        border-color: #e7eaec;
        border-image: none;
        border-style: solid solid none;
        border-width: 1px 0;
        clear: both;
    }
    .ibox-heading {
        background-color: #f3f6fb;
        border-bottom: none;
    }
    .red{
        color: red;
    }
    /deep/ .el-card__header{
        padding: 6px 20px;
    }
</style>
